<?php
// +----------------------------------------------------------------------
// | @filename RoleLogic.php
// +----------------------------------------------------------------------
// | @author 落花轻舞问君愁 <mwcx1990@qq.com>
// +----------------------------------------------------------------------
// | @datetime 2021-10-29 17:36:33
// +----------------------------------------------------------------------
// | @Description
// +----------------------------------------------------------------------

namespace Addons\Backend\Logics;


use Addons\Backend\Repositories\AdminUserRepository;
use Addons\Backend\Repositories\RoleRepository;
use Addons\Backend\Transformers\RoleTransformer;

class RoleLogic extends BaseLogic
{
    protected $roleRepository;
    protected $roleTransformer;
    protected $adminUserRepository;

    public function __construct(RoleRepository $roleRepository, AdminUserRepository $adminUserRepository, RoleTransformer $roleTransformer)
    {
        $this->roleRepository = $roleRepository;
        $this->adminUserRepository = $adminUserRepository;
        $this->roleTransformer = $roleTransformer;
    }

    /**
     * 获取角色列表
     * @param $filters
     * @return array
     */
    public function list($filters): array
    {
        $roles = $this->roleRepository->queryList($filters);
        return $this->success(fractal($roles, $this->roleTransformer)->toArray());
    }

    /**
     * 所有角色
     */
    public function all(): array
    {
        $roles = $this->roleRepository->all();
        return $this->success(fractal($roles, $this->roleTransformer)->toArray());
    }

    /**
     * 创建角色
     * @param $data
     * @return array
     */
    public function create($data): array
    {
        $role = $this->roleRepository->create($data);
        return $this->success(fractal($role, $this->roleTransformer)->toArray(), '创建角色操作成功');
    }

    /**
     * 更新角色
     * @param $data
     * @return array
     */
    public function update($data): array
    {
        $role = $this->roleRepository->update($data);
        return $this->success(fractal($role, $this->roleTransformer)->toArray(), '更新角色操作成功');
    }

    /**
     * 删除角色
     * @param $id
     * @return array
     */
    public function delete($id): array
    {
        $role = $this->roleRepository->findById($id);

        if (empty($role)) {
            return $this->failed('角色不存在');
        }

        return $this->roleRepository->delete($id) ? $this->success([], '删除角色操作成功') : $this->failed([], '删除角色操作失败');
    }

    /**
     * 给角色分配权限
     * @param $data
     * @return array
     */
    public function assignPermissions($data): array
    {
        $this->roleRepository->assignPermissions($data['id'], $data['permissions']);
        return $this->success([], '分配权限操作成功');
    }
}
